package com.team.engine.fileupload.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.StrutsConstants;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.opensymphony.xwork2.inject.Inject;
import com.team.engine.common.view.BaseActionAbs;
import com.team.engine.fileupload.service.FileuploadServiceImpl;

/**
 * 文件上传操作action
 * @author MengLH
 * @data 2010-6-9
 */

public class FileuploadAction extends BaseActionAbs{
	
	private static final long serialVersionUID = -7157922578905616680L;
	
	@Resource(name="fileuploadServiceImpl")
	private FileuploadServiceImpl fileuploadService;
//	private Collection<TFileGroup> coll = new ArrayList<TFileGroup>();
	private FileuploadDomain fileuploadDomain;
	
	/**
	 * 上传的文件对象集合
	 */
	private List<File> file;
	
	/**
	 * 上传的文件类型
	 */
	private List<String> fileContentType;
	
	/**
	 * 上传的文件名
	 */
	private List<String> fileFileName;
	
	public List<File> getFile() {
		return file;
	}

	public List<String> getFileContentType() {
		return fileContentType;
	}

	public List<String> getFileFileName() {
		return fileFileName;
	}

	public String getMaxSize() {
		return maxSize;
	}

	private String maxSize;

	
	public String fileuploadExecute() {

		String filename = null;
		String savedir = this.fileuploadDomain.getSaveDir()==null || fileuploadDomain.getSaveDir().length()==0?"upload":fileuploadDomain.getSaveDir();
		String contextPath = this.servletContext.getRealPath("/"+savedir)+"/";
		
		for (int i = 0; i < this.file.size(); i++) {
			filename = this.fileFileName.get(i);
			
			if( ! this.isFileType(fileContentType.get(i))){
				fileuploadDomain.setFailureFileName(filename);
				return fileuploadDomain.getFailureActionPath();
			}
			
			File fileItem = this.file.get(i);
			if (this.isFileSize(fileItem)) {
				fileuploadDomain.setFailureFileName(filename);
				return fileuploadDomain.getFailureActionPath();
			}
			
			if( ! this.isFileRepeat(filename, contextPath)){
				fileuploadDomain.setFailureFileName(filename);
				return fileuploadDomain.getFailureActionPath();
			}
			
			BufferedInputStream buffis = null;
			BufferedOutputStream buffos = null;
			
			try {
				File destFile = new File(contextPath, filename);
				InputStream is = new FileInputStream(fileItem);
				buffis = new BufferedInputStream(is);

				OutputStream os = new FileOutputStream(destFile);
				buffos = new BufferedOutputStream(os);

				// 此处byte数组大小，是根据系统磁盘格式中的簇大小设置，windows NTFS格式在分区大于2G时，默认簇大小是4KB
				// 减少磁盘碎片产生，减少硬盘磁头移动，减少寻道时间
				byte[] buffer = new byte[4096];
				int length = 0;
				while ((length = buffis.read(buffer)) > 0) {
					buffos.write(buffer, 0, length);
				}

			} catch (FileNotFoundException e) {
				e.printStackTrace();
				//失败的文件名
				fileuploadDomain.setFailureFileName(filename);
				return fileuploadDomain.getFailureActionPath();
			} catch (IOException e) {
				e.printStackTrace();
				fileuploadDomain.setFailureFileName(filename);
				return fileuploadDomain.getFailureActionPath();
			} finally {
				try {
					buffis.close();
					buffos.close();
				} catch (IOException e) {
					e.printStackTrace();
					return fileuploadDomain.getFailureActionPath();
				}
			}
		}
		return SUCCESS;
	}

	/**
	 * 验证文件大小
	 * @return
	 */
	protected boolean isFileSize(File file){
		String maxSizeTmp = this.fileuploadDomain.getMaxSize()==null?this.maxSize:fileuploadDomain.getMaxSize();
		return file.length() > Long.parseLong(maxSizeTmp);
	}
	
	/**
	 * 验证文件类型
	 * @return
	 */
	protected boolean isFileType(String fileContentType){
		String[] filetype = this.fileuploadDomain.getFiletype();
		if(filetype == null || filetype[0].equals("*"))
			return true;
		
		for (String type : fileuploadDomain.getFiletype()) {
			if( ! fileContentType.contains(type.toLowerCase()))
				return false;
		}
		return true;
	}
	
	/**
	 * 验证文件是否重名，即保存的目录中，是否有相同文件名及其类型的文件
	 * @return
	 */
	protected boolean isFileRepeat(String filename, String path){
		
		String[] list = new File(path).list();
		boolean flag = System.getProperty("sun.desktop").equals("windows")?true:false;
		for(String s: list){
			
			if(flag && s.toLowerCase().equalsIgnoreCase(filename)){
				if(new File(path + s).isFile())
					return false;
			}
			
			if( ! flag && s.equals(filename)){
				if(new File(path + s).isFile())
					return false;
			}
		}
		
		return true;
	}
	
	@Inject(StrutsConstants.STRUTS_MULTIPART_MAXSIZE)
    public void setMaxSize(String maxSize) {
        this.maxSize = maxSize;
    }
	
	public void setFileFileName(List<String> fileFileName) {
		this.fileFileName = fileFileName;
	}

	public void setFile(List<File> file) {
		this.file = file;
	}

	public FileuploadDomain getFileuploadDomain() {
		return fileuploadDomain;
	}

	public void setFileContentType(List<String> fileContentType) {
		this.fileContentType = fileContentType;
	}

	public void setFileuploadDomain(FileuploadDomain fileuploadDomain) {
		this.fileuploadDomain = fileuploadDomain;
	}

	public void setFileuploadService(FileuploadServiceImpl fileuploadService){
		this.fileuploadService = fileuploadService;
	}
}
